package com.march.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.march.common.R;
import com.march.dto.DishDTO;
import com.march.entry.Category;
import com.march.entry.Dish;
import com.march.service.CategoryService;
import com.march.service.DishFlavorService;
import com.march.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> add(@RequestBody  DishDTO dishDto){
        // System.out.println(dishDto);
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDTO> dishDTOPage = new Page<>();

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        // 添加过滤条件
        lqw.like(name!=null,Dish::getName,name);
        //执行分页查询
        dishService.page(pageInfo,lqw);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDTOPage,"records");
//
        List<DishDTO> dishDTO = pageInfo.getRecords().stream().map(item -> {
            DishDTO dishDto = new DishDTO();
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            BeanUtils.copyProperties(item, dishDto);
            return dishDto;
        }).collect(Collectors.toList());

        dishDTOPage.setRecords(dishDTO);

        return R.success(dishDTOPage);
    }

    /*
    * 根据id查询菜品信息和对应的口味信息
    * */
    @GetMapping("/{id}")
    public R<DishDTO> getByid(@PathVariable Long id){

        DishDTO byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /*
     * 修改菜品
     * */
    @PutMapping
    public R<String> update(@RequestBody DishDTO dishDTO){

        dishService.updateWithFlavor(dishDTO);
        return R.success("修改成功");
    }

    @GetMapping
    public R<List<Dish>> list(Dish dish){

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,dish.getCategoryId());
        //查询分类id列表
        List<Dish> dishList = dishService.list(lqw);
        return R.success(dishList);
    }
}
